import { ref } from 'vue'
import { restHelperInstance } from '@/composables/useGeoHelper'
import type { IStyle } from 'geoserver-helper/interface'

export default function useStylesModal() {
    const styleList = ref<IStyle.StyleInfoOfList[]>([])
    const sortStyleList = ref<Record<string, IStyle.StyleInfoOfList[]>>({})

    /**
     * @description: 获取全量样式列表
     * @param {boolen} refreshData 是否更新数据（使用实时数据）
     * @param {string} workspace 工作空间
     * @return {*}
     */
    function getStyleListAll(refreshData = false, workspace?: string): Promise<IStyle.StyleInfoOfList[]> {
        if (
            refreshData ||
            (!workspace && styleList.value.length === 0) ||
            (workspace && sortStyleList.value[workspace]!.length === 0)
        ) {
            return new Promise<IStyle.StyleInfoOfList[]>((resove, reject) => {
              restHelperInstance.getStylesListApi(workspace)
                    .then(res => {
                        if (res.styles) {
                            const tempStyleList = res.styles.style
                            if (workspace) {
                                sortStyleList.value[workspace] = tempStyleList
                            } else {
                                styleList.value = tempStyleList
                            }
                            resove(tempStyleList)
                        }
                    })
                    .catch(() => {
                        reject(false)
                    })
            })
        } else {
            if (!workspace) {
                return Promise.resolve(styleList.value)
            } else {
                return Promise.resolve(sortStyleList.value[workspace] as IStyle.StyleInfoOfList[])
            }
        }
    }

    return { styleList, sortStyleList, getStyleListAll }
}
